/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.yourorghere.module5;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Paint;
import java.awt.Point;
import java.awt.RenderingHints;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ConnectException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import javax.swing.JComponent;
import javax.swing.JOptionPane;
import org.openide.util.Exceptions;

/**
 *
 * @author Anil Raju
 */
public class PaintCanvas  extends JComponent implements Runnable,MouseListener, MouseMotionListener,MouseWheelListener  {
static int  conn=0;
   static Socket soc;
    static ServerSocket ss;
     private int diam = 10;
    private Paint paint = Color.BLUE;
    private BufferedImage backingImage;
    private Point last;
    PrintWriter Out;
    Thread t;
    int wr;
      private int ipnotset=1;
    private BufferedReader in;
   
    private int ipnotsetS;
    public PaintCanvas() {
  
        addMouseListener(this);
        addMouseMotionListener(this);
        addMouseWheelListener(this);
        setBackground(Color.WHITE);

    }  
    
    public int shareClient()
    {
           do {

                try {
                    InetAddress ip;

                    String inputValue = JOptionPane.showInputDialog("Enter IP address of server");
if(inputValue==null)
   return 0;             
    ip = InetAddress.getByName(inputValue);
                   soc = new Socket(ip,9080);
                   ipnotset=1;
                   conn=1;
                }

catch(UnknownHostException ue){
    ipnotset = 0;
    System.out.println("unkonwww");
}
                catch(ConnectException ie){
                    ipnotset = 0;
    System.out.println("unkonwww");
}


                catch (IOException ex) {
                    ipnotset = 0;
                    Exceptions.printStackTrace(ex);
                    System.out.println("could not read frm in.read");
                }
                
            } while (ipnotset == 0);

       
         t=new Thread(this);
    t.start();
    return 1;
    }
     public int shareServer()
    {
         
           do {

                try {
                   

                    int inputValue = JOptionPane.showConfirmDialog(null,"Would you like to start server", "choose one", JOptionPane.YES_NO_OPTION);
                    System.out.println(inputValue);
if(inputValue==1)
   return 0;             
   ss = new ServerSocket(9080);
           
                   ipnotsetS=1;
               
                   System.out.println("hello");
                }

catch(UnknownHostException ue){
    ipnotsetS = 0;
    System.out.println("unkonwww");
}
                catch(ConnectException ie){
                    ipnotsetS = 0;
    System.out.println("unkonwww");
}


                catch (IOException ex) {
                    ipnotsetS = 0;
                    Exceptions.printStackTrace(ex);
                    System.out.println("could not read frm in.read");
                }
                
            } while (ipnotsetS == 0);

       
         t=new Thread(this);
    t.start();
    return 1;
    }
     public void setBrush(int diam) {
        this.diam = diam;
    }
     
      public void setDiam(int val) {
        if(val<1)
          this.diam = 1;
        else
            this.diam=val;
    }
    
    public int getDiam() {
        return diam;
    }
    
    public void setPaint(Paint c) {
        this.paint = c;
    }
    
    public Paint getPaint() {
        return paint;
    }
    
    public Color getColor() {
        if (paint instanceof Color) {
            return (Color) paint;
        } else {
            return Color.BLACK;
        }
    }
    
    
     public void clear() {
        backingImage = null;
        repaint();
    }
    
    public BufferedImage getImage() {
        int width = Math.min(getWidth(), 1600);
        int height = Math.min(getHeight(),1200);
        if (backingImage == null || backingImage.getWidth() != width || backingImage.getHeight() != height) {
            BufferedImage old = backingImage;
            backingImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB_PRE);
            Graphics g = backingImage.getGraphics();
            g.setColor(Color.WHITE);
            g.fillRect(0, 0, width, height);
            if (old != null) {
                ((Graphics2D) backingImage.getGraphics()).drawRenderedImage(old,
                        AffineTransform.getTranslateInstance(0, 0));
            }
        }
        return backingImage;
    }
    
    public void paint(Graphics g) {
        Graphics2D g2d = (Graphics2D) g;
        g2d.drawRenderedImage(getImage(), AffineTransform.getTranslateInstance(0,0));
    }
    
    public void mouseClicked(MouseEvent e) {
        Point p = e.getPoint();
        if(conn==1)
        {send(p);
        }
        Graphics2D g = getImage().createGraphics();
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g.setPaint(getPaint());
        g.setStroke(new BasicStroke(diam, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
        if (last == null) {
            last = p;
        }
        g.drawLine(last.x, last.y, p.x, p.y);
        repaint(Math.min(last.x, p.x) - diam / 2 - 1,
                Math.min(last.y, p.y) - diam / 2 - 1,
                Math.abs(last.x - p.x) + diam + 2,
                Math.abs(last.y - p.y) + diam + 2);
        last = p;
    }
    
    public void mouseClicked(int x,int y) {
        Point p = new Point(x,y);
       
        Graphics2D g = getImage().createGraphics();
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g.setPaint(getPaint());
        g.setStroke(new BasicStroke(diam, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
        if (last == null) {
            last = p;
        }
        g.drawLine(last.x, last.y, p.x, p.y);
        repaint(Math.min(last.x, p.x) - diam / 2 - 1,
                Math.min(last.y, p.y) - diam / 2 - 1,
                Math.abs(last.x - p.x) + diam + 2,
                Math.abs(last.y - p.y) + diam + 2);
        last = p;
    }
    
    public void mousePressed(MouseEvent e) {
    }
    
    public void mouseReleased(MouseEvent e) {
    }
    
    public void mouseEntered(MouseEvent e) {
    }
    
    public void mouseExited(MouseEvent e) {
    }
    
    public void mouseDragged(MouseEvent e) {
        mouseClicked(e);
    
    }
    
    public void mouseMoved(MouseEvent e) {
        last = null;
        Point pp=new Point(-5,-5);
      if(conn==1)
        send(pp);

    }
     public void mouseMoved() {
        last = null;
    }
    JComponent createBrushSizeView() {
        return new BrushSizeView();
    }

    void stopshare() {
       conn=0;
       
    }
    
    
    private class BrushSizeView extends JComponent {
        
        public boolean isOpaque() {
            return true;
        }
        
        public void paint(Graphics g) {
            ((Graphics2D) g).setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            g.setColor(getBackground());
            g.fillRect(0,0,getWidth(),getHeight());
            Point p = new Point(getWidth() / 2, getHeight() / 2);
            int half = getDiam() / 2;
            int diam = getDiam();
            g.setColor(getColor());
            g.fillOval(p.x - half, p.y - half, diam, diam);
        }
        
        public Dimension getPreferredSize() {
            return new Dimension(32, 32);
        }
        
        public Dimension getMinimumSize() {
            return getPreferredSize();
        }
        
    }

    public void mouseWheelMoved(MouseWheelEvent e) {
        int wr=e.getWheelRotation();
        if(wr<0)
           this.diam++;
        else
        {
            if(this.diam > 1)
            this.diam--;
        }  
            
    }

     public void run() {
       try{
    
 
                if(ipnotsetS==1)
                {soc = ss.accept(); 
               conn=1;
                }
            Out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(soc.getOutputStream())), true);
            System.out.println("client started");
            in = new BufferedReader(new InputStreamReader(soc.getInputStream()));
            while (true) {
               

                    int x;
                    int y;
                    System.out.println("insid while true goint to read x value");
                    x = Integer.parseInt(in.readLine());
                    y = Integer.parseInt(in.readLine());
                    this.diam = Integer.parseInt(in.readLine());

                    System.out.println("x=" + x + " y=" + y);
                    if (x == -1) {
                        clear();
                    } else if (x == -5) {
                        mouseMoved();
                    } else {
                        mouseClicked(x, y);
                    }
               
              
            }
}
       catch(IOException EX)
       {
           System.out.println("in and out error");
           
       }
      
          
        
    
       
     }
    
    public void send(Point p)
    {
       
           
            
            System.out.println(p.toString());
            System.out.println(p.x);
            System.out.println(p.y);
            
           Out.println(p.x);
           Out.flush();
           
           
            Out.println(p.y);
           Out.flush();
             System.out.println("x="+p.x+" y="+p.y);
        Out.println(this.diam);
    }

    }
    


